<template>
  <div>
    <!-- 工具栏 -->
    <div class="tools">
      <!-- @click="addUserFormVisible = true"打开嵌套的新增表单 -->
      <el-button
        class="addUserButton"
        type="primary"
        @click="addUserFormVisible = true"
        icon="el-icon-circle-plus-outline"
        >新增</el-button
      >
      <el-button 
        style="margin-top: 10px; margin-right: 40px"
        type="primary"
        @click="handleDelete"
        icon="el-icon-delete"
        >删除</el-button
      >
      <el-input
        v-model="queryUserVo.userName"
        style="width: 200px; margin-right: 20px"
        placeholder="用户名"
      ></el-input>
       <el-select style="margin-right: 20px" v-model="status" placeholder="菜单类型">
        <el-option value="0" label="菜单">菜单</el-option>
        <el-option value="1" label="目录">目录</el-option>
        <el-option value="2" label="功能">功能</el-option>
      </el-select>
      <!-- status的初始值是谁就会默认选中谁 没设label的话选择后就会变成value1、2 -->
      <el-select v-model="status" placeholder="全部" style="margin-right: 20px">
        <el-option value="" label="全部">全部</el-option>
        <el-option value="1" label="有效">有效</el-option>
        <el-option value="0" label="无效">无效</el-option>
      </el-select>

      <el-button type="primary" icon="el-icon-search" @click="queryUser()"
        >搜索</el-button
      >
      <br />
      
      <!-- 新增用户的对话框 -->
      <el-dialog title="添加用户" :visible.sync="addUserFormVisible">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="userName">
            <el-col :span="11">
              <el-input v-model="ruleForm.userName"></el-input>
            </el-col>
          </el-form-item>
          <!-- required添加✳号 -->
          <el-form-item label="姓名" prop="name">
            <el-col :span="11">
              <el-input v-model="ruleForm.name"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-col :span="11">
              <el-input type="password" v-model="ruleForm.password"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPassword">
            <el-col :span="11">
              <el-input
                type="password"
                v-model="ruleForm.checkPassword"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formSex" placeholder="">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="电话" prop="phoneNumber">
            <el-col :span="11">
              <el-input v-model="ruleForm.phoneNumber"></el-input>
            </el-col>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-col :span="11">
              <el-input v-model="ruleForm.email"></el-input>
            </el-col>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="redio">
              <el-radio :label="1">有效</el-radio>
              <el-radio :label="0">无效</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input type="textarea" v-model="ruleForm.note"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >提 交</el-button
            >
            <el-button @click="resetForm('ruleForm')">重 置</el-button>
            <el-button @click="addUserFormVisible = false">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 编辑用户的对话框 -->
      <el-dialog title="编辑用户" :before-close="resetRuleForm" :visible.sync="editUserFormVisible">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" >
            <el-col :span="11">
              <el-input v-model="ruleForm.userName" disabled></el-input>
            </el-col>
          </el-form-item>
          
          <el-form-item label="姓名" prop="name">
            <el-col :span="11">
              <el-input v-model="ruleForm.name"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="密码" prop="password1">
            <el-col :span="11">
              <el-input type="password" v-model="ruleForm.password"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPassword">
            <el-col :span="11">
              <el-input
                type="password"
                v-model="ruleForm.checkPassword"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formSex">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="电话" prop="phoneNumber">
            <el-col :span="11">
              <el-input v-model="ruleForm.phoneNumber"></el-input>
            </el-col>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-col :span="11">
              <el-input v-model="ruleForm.email"></el-input>
            </el-col>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="redio">
              <el-radio :label="1">有效</el-radio>
              <el-radio :label="0">无效</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input type="textarea" v-model="ruleForm.note"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitEditUserForm('ruleForm')"
              >提 交</el-button
            >
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <el-button @click="resetRuleForm">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      
    </div>
    <!-- 分页表格 -->
    <div>
      <el-table
        height="410"
        ref="multipleTable"
        :data="menus"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="left" width="55">
        </el-table-column>
        <el-table-column label="序号" align="left" type="index" width="70">
          <!-- <template slot-scope="scope">{{ scope.row.date }}</template> -->
        </el-table-column>
        
        <el-table-column
          prop="menuName"
          label="菜单名称"
          show-overflow-tooltip
          align="left"
          width="100"
        >
        </el-table-column>
        <el-table-column prop="parentMenu" label="上级菜单" align="left" width="100">
         
        </el-table-column>
        <el-table-column
          prop="menuType"
          label="菜单类型"
          align="left"
          width="120"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="menuIdentify"
          label="菜单标识"
          width="110"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="menuAddr"
          label="菜单地址"
          show-overflow-tooltip
          align="left"
          width="110"
        >
        </el-table-column>
        <el-table-column
          prop="menuIcon"
          label="图标"
          show-overflow-tooltip
          align="left"
          width="90"
        >
        </el-table-column>
        <el-table-column
          prop="sortNumber"
          align="left"
          label="排序号"
          show-overflow-tooltip
          width="110"
        >
        </el-table-column>
        <el-table-column
          prop="status"
          align="left"
          label="状态"
          show-overflow-tooltip
          width="70"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">无效</span>
            <span v-if="scope.row.status == 1">有效</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              align="left"
              type="primary"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              align="left"
              type="danger"
              @click="handleDelete2(scope.row)"
              >删除</el-button
            >

          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页页码等 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[7, 15, 30, 60, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
// import {mapMutations} from "vuex";
export default {
  name: "MenuManage",
  data() {
    // 校验两次的输入密码是否一致
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validatePass3 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      }else {
        callback();
      }
    }
    //自定义的邮箱和手机验证规则
    let checkEmail = (rule, value,callback) =>{//验证邮箱
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if(this.ruleForm.email != '' && !regEmail.test(this.ruleForm.email) && this.ruleForm.email != null) {
        callback(new Error('请输入有效的邮箱')); 
      }else{
         callback();
      }
    }
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      status: "",
      createTime: "",
      // 初始为第一页
      currentPage: 1,
      // 总页数，从后台获取
      total: 1,
      // 每页的数量
      pageSize: 7,
      // 分页内容
      menus: [],
      // 被选中的用户数组
      userSelected: [],
      // 模糊查询的用户名
      // 根据时间查询的数组
      queryCreateTime: [],
      queryUserVo: {
        //模糊查询的对象
        userName: "",
        name: "",
        beginTime: "",
        endTime: "",
        status: "",
      },
      // 添加员工对话框是否可见
      addUserFormVisible: false,
      // 编辑员工的对话框是否可见
      editUserFormVisible: false,
      // 新增和编辑用户表单的性别
      formSex: "1",
      //新增和编辑用户表单的状态
      redio: 1,
      // 新增用户和编辑用户表单里的值
      ruleForm: {
        userName: "",
        name: "",
        password: "",
        checkPassword: "",
        phoneNumber: "",
        sex: "",
        email: "",
        status: "",
        note: "",
      },
      formLabelWidth: "120px",
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "用户名长度为6~20个英文字母或汉字组成",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
            if(value != ""){
              
              this.getRequest("/user/getOne?userName="+value).then(resp=>{
                if(resp.data!=null){
                  callback(new Error("用户已存在"));
                }else{
                  callback();
                }
              })
            }
            },
            trigger: "blur"
          }
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "姓名长度为2~50个英文字母或汉字组成",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "密码长度为6~20个英文字母或汉字组成",
            trigger: "blur",
          },
        ],
        password1: [
          { validator: validatePass3, trigger: "blur" },
        ],
        checkPassword: [{ validator: validatePass2, trigger: "blur" }],
        phoneNumber: [
          { max: 50, message: "手机号不能超过50个字符", trigger: "blur" },
          {validator:function(rule,value,callback){
	            if(/^1[34578]\d{9}$/.test(value) == false && value != "" && value != null){
	                callback(new Error("请输入正确的手机号"));
	            }else{
	                callback();
	            }
          }, trigger: 'blur'}
        ],
        email: [
          { max: 200, message: "邮箱不能超过200个字符", trigger: "blur" },
          {validator: checkEmail, trigger: "blur" }
        ],
      },
    };
  },

  // 钩子函数获取数据
  mounted() {
    this.initMenus();
  },
  methods: {
    //  复选框
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 状态选择
    handleSelectionChange(val) {
      //提取选中用户的id
      this.userSelected = val;
    },
    //    切换每页的数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.initMenus();
    },
    // 模糊查询用户
    queryUser() {
      //把选中的状态赋值给查询对象
      this.queryUserVo.status = this.status;

      if (this.queryCreateTime) {
        //把选中的时间赋值给查询对象
        this.queryUserVo.beginTime = this.queryCreateTime[0];
        this.queryUserVo.endTime = this.queryCreateTime[1];
      } else {
        this.queryUserVo.beginTime = "";
        this.queryUserVo.endTime = "";
      }
      this.initMenus();
    },
    // 编写员工信息
    handleEdit(row) {
      // 把当前用户信息归到表单
      this.ruleForm.userName = row.userName;
      this.ruleForm.name = row.name;
      this.ruleForm.password = row.password;
      this.ruleForm.checkPassword = row.password;
      this.formSex = row.sex + "";
      this.ruleForm.phoneNumber = row.phoneNumber;
      this.ruleForm.email = row.email;
      this.redio = row.status;
      this.ruleForm.note = row.note;
      this.editUserFormVisible = true;
    },
    // 编写完重置对话框的表单信息
    resetRuleForm() {
      this.ruleForm.userName = "";
      this.ruleForm.name = "";
      this.ruleForm.password = "";
      this.ruleForm.checkPassword = "";
      this.formSex = "1";
      this.ruleForm.phoneNumber = "";
      this.ruleForm.email = "";
      this.ruleForm.note = "";
      this.editUserFormVisible = false;
      this.redio = 1;
    },
    // 删除某一个员工
    handleDelete2(row) {
      // 提示是否永久删除该用户
      this.$confirm("是否要永久删除" + row.name + "的信息", "提示", {
        confirmButtonText: "是的",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteRequest("/user/delete?ids=" + row.userId).then((resp) => {
            if (resp) {
              this.initMenus();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除用户
    handleDelete() {
      if (this.userSelected.length != 0) {
        // 提示是否永久删除该用户
        this.$confirm("删除后不可恢复，是否继续", "提示", {
          confirmButtonText: "继续",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            let ids = "?";
            this.userSelected.forEach((item) => {
              ids += "ids=" + item.userId + "&";
            });
            this.deleteRequest("/user/delete" + ids).then((resp) => {
              if (resp) {
                this.initMenus();
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      } else {
        this.$message.error("请选择用户");
      }
    },
    // 跳转页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initMenus();
    },
    // 初始化用户
    initMenus() {
      this.getRequest(
        "/menu/selectAll?currentPage=" +
          this.currentPage +
          "&pageSize=" +
          this.pageSize,
        this.queryUserVo
      ).then((resp) => {
        if (resp.data) {
          this.menus = resp.data.list;
          this.total = resp.data.total;
        }
      });
    },
    // 编辑用户提交表单
    submitEditUserForm(ruleForm) {
      console.log(this.ruleForm.email);
      // ruleForm为添加用户的表格,不合法的话不提交
      this.$refs[ruleForm].validate((valid) => {       
        if (valid) {
          this.ruleForm.sex = this.formSex;
          this.ruleForm.status = this.redio;         
          this.postRequest("/user/edit", this.ruleForm).then((resp) => {
            if (resp.data) {
              // 编辑提交后关闭弹窗初始化用户信息，重置表单
              this.addUserFormVisible = false;
              this.initMenus();
              this.resetRuleForm();
            }
          });
        } else {
          return false;
        }
      });
    },
    //添加用户提交表单
    submitForm(ruleForm) {
      // ruleForm为添加用户的表格,不合法的话不提交
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          this.ruleForm.sex = this.formSex;
          this.ruleForm.status = this.redio;
          this.postRequest("/user/add", this.ruleForm).then((resp) => {
            if (resp.data) {
              this.addUserFormVisible = false;
              this.initMenus();
              this.resetForm(ruleForm);
            }
          });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
.tools {
  margin-top: 10px;
}
.addUserButton {
  margin-right: 20px;
}
</style>
